<!--
 * 用户注册页面
-->
<template>
<div class="wrapper" >
 <div class="login-box">

      <div class="title">
        <b><span style="color: #e75c09">注 册</span></b>
      </div>
      <div style="margin-top: 30px">
        <el-form label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model.trim="user.username" aria-required="true"></el-input>
          </el-form-item>
          <el-form-item label="密码" style="margin-top: 25px">
            <el-input v-model.trim="user.password" show-password aria-required="true"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" style="margin-top: 25px">
            <el-input v-model.trim="user.confirmPassword" show-password aria-required="true"></el-input>
          </el-form-item>
          <el-form-item style="margin: 30px 80px">
            <el-button type="success" @click="onSubmit">注册</el-button>
            <el-button @click="$router.push('/login')">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
 </div>
</div>
</template>

<script>

export default {
  name: 'Login',
  data () {
    return {
      user: {}
    }
  },
  methods: {
    async onSubmit () {
      // 验证用户名和密码不能为空
      if (!this.user.username || this.user.username.trim() === '') {
        this.$message.error('用户名不能为空')
        return false
      }
      if (!this.user.password || this.user.password.trim() === '') {
        this.$message.error('密码不能为空')
        return false
      }
      if (!this.user.confirmPassword || this.user.confirmPassword.trim() === '') {
        this.$message.error('确认密码不能为空')
        return false
      }
      // 验证两次密码是否一致
      if (this.user.password !== this.user.confirmPassword) {
        this.$message.error('两次密码不一致')
        return false
      }
      try {
        // 直接调用注册接口，后端会检查用户名是否已存在
        const res = await this.$http.post('/register', this.user)
        if (res.code === 200) {
          this.$message.success('注册成功')
          this.$router.push('/login')
        } else {
          // 后端返回的错误信息，包括"该用户名已存在"等
          this.$message.error(res.msg || '注册失败')
        }
      } catch (error) {
        console.error('注册失败:', error)
        this.$message.error('注册失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.wrapper {
  height: 100vh;
  background-image: url("@/assets/img/login_back.png");
  overflow: auto;
}
.login-box {
  margin: 220px auto;
  padding: 40px;
  width: 450px;
  height: 310px;
  background-color: #ffffff;
  border-radius: 10px;
}
.title {
  text-align: center;
  margin-top: 10px;
  font-size: 25px;
  color: #000000
}
</style>
